
// 底部导

var frames = ['index', 'user'];
function fnChange(index) {
    var footer_h = $api.offset($api.dom('footer')).h;
    for (var i = 0; i < 2; i++) {
        if (index == i) {
            api.openFrame({
                name: frames[i],
                url: './html/' + frames[i] + '.html',
                bounces: true,
                vScrollBarEnabled: false,
                hScrollBarEnabled: false,
                  historyGestureEnabled:true,
                rect: {
                    x: 0,
                    y: 0,
                    w: 'auto',
                    h: api.frameHeight - footer_h
                }
            });
            $(".aui-bar-tab-item").removeClass("aui-active");
            $(".aui-bar-tab-item").eq(i).addClass("aui-active");

        } else {
            api.setFrameAttr({
                name: frames[i],
                hidden: true
            });
        }
    }
}

// tab页
function initFrameGroup() {
    // var framesArr = [
    //   {
    //      name: 'index',
    //      url: './html/index.html',
    //      bounces: true,
    //        historyGestureEnabled:true,
    //   },
    //   {
    //      name: 'user',
    //      url: './html/user.html',
    //      bounces: true,
    //        historyGestureEnabled:true,
    //
    //   }
    // ];
    //
    // var footer_h = $api.offset($api.dom('footer')).h;
    // api.openFrameGroup({
    //    name: 'frame_group',
    //    scrollEnabled: true,
    //    rect: {
    //        x: 0,
    //        y: 0,
    //        w: 'auto',
    //        h: api.winHeight-footer_h
    //    },
    //    frames: framesArr
    // });
    fnChange(0);

}


// 打开一个页面
function openFrame(name,url,bounces,params){
  params=params?params:{};
  api.openWin({
      name: name,
      url: url,
      pageParam:params,
      bounces: bounces?true:false,
      rect: {
          x: 0,
          y: 0,
          w: 'auto',
          h: 'auto'
      },

      animation:{
          type:"push",                //动画类型（详见动画类型常量）
          subType:"from_right",       //动画子类型（详见动画子类型常量）
          duration:300                //动画过渡时间，默认300毫秒
      }
  })
}

// 关掉一个页面
function closeFrame(){
    api.closeWin();
}


function webView(url,title) {
  if(window.browser){
    var  browser = window.browser;
  }else{
    var browser = api.require('webBrowser');
    window.browser = browser;
    app.log("browser","browser");
  }

  var userInfo = app.getUserInfo();
  var store_id = userInfo.store_id;
  var token = userInfo.token;
  url = url.replace("{store_id}",store_id);
  var endUrl="";
  if(url.indexOf("#")>-1){
    var urls = url.split("#");
    url = urls[0];
    endUrl="#"+urls[1];
    app.log("urls",urls);
  }
  if(url.indexOf("?")>-1){
     url = url.replace("?","?from=webapp&from_wx_app=1&token="+token+"&");
  }else{
     url+="?from=webapp&from_wx_app=1&token="+token;
  }
  url+=endUrl;
  app.log("url",url);
  // openFrame("webView","./webView.html",0,{url:url,title:title});
  // return;
  // app.log("url",url);
  browser.open({
      url: url,
      headers:{
        token:token
      },
      titleBar:{
          bg:'#fdd903',
          textColor:'#ffffff'
      }
  });
}
/*
 * APICloud JavaScript Library
 * Copyright (c) 2014 apicloud.com
 */
(function(window){

   var app ={
     params : {
            versions: '6.7',
            userVersions: '2.4',
            urlChangeFromComponent:1,
            debug: true,
            urlCache: {},
            loadPage: 0,
            plugUrl: '/',
            apiDomain: 'https://www.bestsmartbee.com/', //不带"/"
            //domain: 'http://www.codecamp.com',
            loginUrl: 'https://login.bestsmartbee.com/',
            //loginUrl: 'http://puxiang.boxphp.me',
     },
     vm:{

     },
     init:function(){
        var user = app.getUserInfo();
        app.log("user:",user);
        if(user.user_id){
          app.checkToken();
        }else{
          openFrame("login","./html/login.html");
        }
     },
     initPushGeTui:function() {
         var pushGeTui = api.require('pushGeTui');
          var user = app.getUserInfo();
        var systemType = api.systemType;
         // 注册设备和应用信息到个推
         pushGeTui.initialize(function(ret) {
             var value = "";
             // 区分通知和消息
             switch (ret.type) {
                 // 返回个推平台上的ID
                 case 'cid':
                    //  value = 'cid:' + ret.cid;
                      app.log("initPushGeTui",value);
                      app.post("apiv2/user_app_msg_push/add",{
                        user_id:user.user_id,
                        store_id:user.store_id,
                        app_account:ret.cid,
                        platform:systemType
                      },function(res){
                        if(res.code!=200){
                           app.alert(res.msg);
                        }
                      });
                     break;
                 // 返回消息内容
                 case 'payload':
                    //  value = 'payload:' + ret.payload;
                     app.log("initPushGeTui payload",ret);
                     // 解析消息体
                     var data = JSON.parse(ret.payload);
                     app.log("initPushGeTui",data);
                     app.revPush(data);
                     break;
                 case 'occurError':
                     value = 'occurError';
                     break;
                 default:
                     break;
             }

         });
      },
    //  推送监听
     listenPush:function(){
           var user = app.getUserInfo();

           var tencentPush = api.require('tencentPush');
          //  var param = {debug:true};
          //  tencentPush.config(param);
           // 需要绑定的账号，若为"*"表示解除之前的账号绑定
           var systemType = api.systemType;
           var account = user.user_id+"_"+systemType;
           var resultCallback = function(ret, err) {
               if (ret.status) {
                  app.post("apiv2/user_app_msg_push/add",{
                    user_id:user.user_id,
                    store_id:user.store_id,
                    app_account:account,
                    platform:systemType
                  },function(res){
                    if(res.code!=200){
                       app.alert(res.msg);
                    }
                  });
               } else {
                   alert("推送注册失败，错误码：" + err.code + "，错误信息：" + err.msg);
               }
           };

           var params = { account: account };
           tencentPush.registerPush(params, resultCallback);


           // 注册消息透传（消息命令字）的接收回调

          var resultCallback = function(ret, err) {
              var customContent = JSON.parse(ret.customContent);
              var data = customContent && customContent.custom1;
              app.revPush(data);
              // app.log("customContent：", data );

          };
          var params = { name: "message" };
          tencentPush.setListener(params, resultCallback);

          // 注册通知被展示的回调
          // var tencentPush = api.require('tencentPush');
          // var resultCallback = function(ret, err) {
          //     alert("收到通知被展示的回调，title：" + ret.title + "，content：" + ret.content + "，customContent：" + ret.customContent + ",activity:" + ret.activity + ",actionType:" + ret.actionType + ",msgid:" + ret.msgid);
          // };
          // var params = { name: "notifactionShow" };
          // tencentPush.setListener(params, resultCallback);
          //
          //
          // // 注册通知被点击的回调
          // var tencentPush = api.require('tencentPush');
          // var resultCallback = function(ret, err) {
          //     alert("收到通知被点击的回调，title：" + ret.title + "，content：" + ret.content + "，customContent：" + ret.customContent + ",activity:" + ret.activity + ",actionType:" + ret.actionType + ",msgid:" + ret.msgid);
          // }
          // var params = { name: "notifactionClick" };
          // tencentPush.setListener(params, resultCallback);
          //
          // // 注册通知被清除的回调
          // var tencentPush = api.require('tencentPush');
          // var resultCallback = function(ret, err) {
          //     alert("收到通知被清除的回调，title：" + ret.title + "，content：" + ret.content + "，customContent：" + ret.customContent + ",activity:" + ret.activity + ",actionType:" + ret.actionType + ",msgid:" + ret.msgid);
          // }
          // var params = { name: "notifactionClear" };
          // tencentPush.setListener(params, resultCallback);

    },
    // 接收推送的消息
    revPush:function(data){
      app.log("revPush");
      console.log(data);
      app.log("revPush type",data.type);
      // 语音报播
      if(data.type=="soud"){
          app.read(data.words,data.repeat);
      }

    },
    //检查TOKEN 是否过期
    checkToken:function(){
       app.get("apiv2/user/checkToken",function(res){
           if(res.code!=200){
               openFrame("login","./html/login.html");
           }else{
             app.initPushGeTui();
             initFrameGroup();
           }
       })
     },
     pager: function(id,callblack) {
        function pagerContent(_this) {
            var bot = 100; //bot是底部距离的高度
            var nDivHight = $(_this).height();
            var nScrollHight = $(_this)[0].scrollHeight;
            var nScrollTop = $(_this)[0].scrollTop;
            // console.log("nScrollTop:",nScrollTop,"nDivHight:",nDivHight,"nScrollTop:",nScrollTop,"bot",bot);
            if (((nScrollTop + nDivHight + bot) >= nScrollHight) && app.params.loadPage == '0') {
                $.isFunction(callblack) ? callblack() : "";
            }
        }
        document.body.addEventListener("touchmove", function(e){
           pagerContent($(id).find(".page-content"));
				});
				document.body.addEventListener("touchend", function(e){
            pagerContent($(id).find(".page-content"));
				});
    },
    // 停语音报播
    stopRead:function(){
      var iflyRecognition = api.require('iflyRecognition');
      // app.cache().set("stopRead",1);
      api.setGlobalData({
          key: 'stopRead',
          value: 1
      });
      iflyRecognition.stopRead();
    },

    // 语音报播
    read:function(words,repeat){
      var iflyRecognition = api.require('iflyRecognition');
        iflyRecognition.createUtility({
          ios_appid: api.loadSecureValue({
                        sync: true,
                        key: 'iflyRecognition_ios_id'
                    }),
          android_appid: api.loadSecureValue({
                        sync: true,
                        key: 'iflyRecognition_android_id'
                    })
      }, function(ret, err) {
          // app.log("iflyRecognition ret",ret);
          if (ret.status) {
            iflyRecognition.read({
                readStr: words,
                speed: 20,
                volume: 100,
                voice: 0,
                rate: 16000,
            }, function(ret, err) {
                app.log("iflyRecognition read",ret);
                if (ret.status) {
                    // ret.speakProgress;
                    app.log("iflyRecognition read",ret);
                    // var stopRead = app.cache().get("stopRead");
                    var stopRead = api.getGlobalData({
                        key: 'stopRead'
                    });
                      app.log("istopRead",stopRead);
                    if(repeat==1 && ret.speakProgress==100 && stopRead!=1){
                       setTimeout(function(){
                         app.read(words,repeat);
                       },2000);
                    }else{
                       app.cache().rm("stopRead");
                    }
                } else {
                    api.alert({ msg: err.msg });
                }
            });
          } else {
              api.alert({ msg: "创建失败" });
          }
      });
    },
    log:function(name,content){
       console.log(name);
       console.log(JSON.stringify(content));
     },
     ajax: function(params) {
               var user = app.getUserInfo();
               var search = {
                  token:user.token,
                  store_id:user.store_id,
               };
               params = params ? params : {};
               if($.isArray(params["data"])){
                   for (var i in params["data"] ) {
                        search.push({
                               name:i,
                               value:params["data"][i]
                           });
                   }

               }else{
                     $.extend(search,params["data"]);
               }
               params["data"] = search;

              app.log("params",params);
               var ajaxTimeoutTest = $.ajax({
                   url: params['url'],
                   type: params['type'],
                   dataType: params['dataType'],
                   data: params['data'],
                   cache: false,
                   timeout: 10000,
                   beforeSend: function() {
                       app.showLoad();
                   },
                   success: function(result) {
                       app.log("result",result);
                       var success = params['success'];
                       typeof(success) == "function" ? success(result): "";
                   },
                   complete: function(msg, status) {
                       // console.log(msg.response);
                       app.hideLoad();
                       if (status == 'timeout') { //超时,status还有success,error等值的情况                       　　　　　
                           ajaxTimeoutTest.abort();
                           app.alert("由于网络原因，请求超时，请刷新网页试试");　　
                           app.saveLog("由于网络原因，请求超时，请刷新网页试试");　　
                       }
                       if (params['cache']) {
                           var key = app.base64_encode(params['url']);
                           var result = msg.response;
                           app.params.urlCache[key] = result;
                           app.cache().set(key, result);
                       }


                   },
                   error: function(XMLHttpRequest, textStatus, errorThrown) {
                       app.saveLog(errorThrown);
                       console.log(errorThrown);
                   }
               });
           },

           //缓存
            cache: function(v) {
                var versions = v ? v : app.params.versions;
                var cacheFun = {
                    set: function(key, data) {
                        var value;
                        key = key + "_" + versions;
                        if (typeof(data) == "object") {
                            data = JSON.stringify(data);
                            value = "obj-" + data;
                        } else {
                            value = "str-" + data;
                        }
                        try {
                            localStorage.setItem(key, value);
                        } catch (err) {
                            if (err.name == 'QuotaExceededError') {
                                localStorage.clear(); //如果缓存已满则清空
                                localStorage.setItem(key, value);
                            }
                        }
                    },
                    rm: function(key) {
                        key = key + "_" + versions;
                        localStorage.removeItem(key);
                    },
                    get: function(key) {
                        key = key + "_" + versions;
                        var value = localStorage.getItem(key);
                        if (value == null) {
                            return null;
                        }
                        var type = value.substr(0, 4);
                        if (type == "str-") {
                            return value.substr(4);
                        }
                        if (type == "obj-") {
                            var data = value.substr(4);
                            return $.parseJSON(data);
                        }
                    },
                    clear: function() {
                        localStorage.clear();
                    }
                };
                return cacheFun;

            },
            //保存错误日志
           saveLog: function(msg) {
               console.log(msg);

           },
            get: function(url, params, callblack) {
                app.showLoad();
                // console.log(params);
                var args = typeof(params) == "object" ? params : {};
                callblack = $.isFunction(params) ? params : callblack;
                var UserInfo = app.getUserInfo();
                if (UserInfo && UserInfo.token) {
                    args.token = UserInfo.token;
                }
                app.ajax({
                    type: 'GET',
                    dataType: 'json',
                    data: args,
                    success: function(res) {
                        // console.log(res);
                        callblack(res);
                    },
                    url: app.params.apiDomain + url,
                });
            },
            post: function(url, params, callblack) {
                app.showLoad();
                // console.log(params);
                var args = typeof(params) == "object" ? params : {};
                callblack = $.isFunction(params) ? params : callblack;
                var UserInfo = app.getUserInfo();
                if (UserInfo && UserInfo.token) {
                    if (args && args.length > 0 && args[0]['name']) {
                        args[args.length] = {
                            name: 'token',
                            'value': UserInfo.token
                        };
                    } else {
                        args['token'] = UserInfo.token;
                    }
                }

                app.ajax({
                    type: 'POST',
                    dataType: 'json',
                    data: args,
                    success: function(res) {
                        callblack(res);
                    },
                    url: app.params.apiDomain + url,
                });
            },
            showLoad:function(){
              api.showProgress({
                  title: '',
                  text: '',
                  modal: false
              });
            },
            hideLoad:function(){
              api.hideProgress();
            },
            alert:function(msg,callblack) {
                api.toast({
                    msg: msg,
                    duration: 2000,
                    location: 'middle'
                });
                callblack?callblack():'';
            },    //用户信息
            getUserInfo: function() {
                var userVersions = app.params.userVersions;
                var UserInfo = app.cache(userVersions).get('UserInfo');
                if (UserInfo && UserInfo.token) {
                    return UserInfo;
                }
                return {};

            },
            setUserInfo: function(userInfo) {
                var userVersions = app.params.userVersions;
                if (userInfo && userInfo.user_id && userInfo.token) {
                    //app.cache(userVersions).rm('UserInfo');
                    //console.log(userInfo.address);
                    var UserInfo = app.cache(userVersions).set('UserInfo', userInfo);
                }
            },
            checkMerchantId:function(){
               var merchantId = app.cache().get('merchantId');
               if(!merchantId){
                 webView("https://wap.bestsmartbee.com/apps/mch_mybank/?store_id={store_id}#/from/app/pid/0");
               }
            }

   };

    window.app = app;

})(window);
